package com.tf.temper.controller;

import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.temper.entity.*;
import com.tf.temper.service.DeviceSettingService;
import com.tf.temper.service.LogeventService;
import com.tf.temper.service.UserinfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 上传比对结果
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "上传人脸比对结果",description="DevuploadresultController")
@RestController
@RequestMapping("/syface")
public class DevuploadresultController extends BaseController
{
    @Autowired
    private LogeventService<LogeventEntity> logeventService;
    @Autowired
    private DeviceSettingService<DeviceSettingEntity> deviceSettingService;
    @Autowired
    private UserinfoService<UserinfoEntity> userinfoService;
    @ApiOperation("上传人脸比对结果接口")
    @PostMapping("/{deviceid}")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public SyfaceReturnEntity<String> syface(@PathVariable("deviceid") String deviceid, @RequestBody String faceentity)
    {
        if(deviceid!=null)
        {
            EntityWrapperHandle<DeviceSettingEntity> ewdevicentity = new EntityWrapperHandle<DeviceSettingEntity>();
            ewdevicentity.eq("deviceid", deviceid);
            DeviceSettingEntity curdevicesetting =  deviceSettingService.selectOne(ewdevicentity);
            if(curdevicesetting!=null&&faceentity!=null)
            {
                boolean isMask = false;
                String  jsontemperature = "";
                String  userId = "";
                String  userName = "";
                String  userType = "";
                int actionCode = 0;
                String action = "";
                String uuid = "";
                String openMsg = "";
                String nationCode = "";
                long screenTime = 0;
                int similarity = 0;
                String img = "";
                try
                {
                    JSONObject faceentityJSON = new JSONObject(faceentity);
                    isMask = faceentityJSON.optBoolean("mask");
                    jsontemperature =  faceentityJSON.optString("temperature");
                    userId = faceentityJSON.optString("userId");
                    userName = faceentityJSON.optString("userName");
                    userType = faceentityJSON.optString("userType");
                    actionCode = faceentityJSON.optInt("actionCode");
                    action = faceentityJSON.optString("action");
                    uuid =  faceentityJSON.optString("uuid");
                    openMsg =  faceentityJSON.optString("openMsg");
                    nationCode =  faceentityJSON.optString("nationCode");
                    screenTime =  faceentityJSON.optLong("screenTime");
                    similarity =  faceentityJSON.optInt("similarity");
                    img =  faceentityJSON.optString("img");
                }
                catch (JSONException e)
                {

                }
                int unlockDelay = curdevicesetting.getUnlockDelay();
                int mask = curdevicesetting.getMask();
                String temperature = curdevicesetting.getTemperature();
                int openDoor = 0;
                if((mask==1&&isMask==true)||mask==0)
                {
                   double settemperature =  Double.parseDouble(temperature);
                   double curtemperature  =  Double.parseDouble(jsontemperature);
                   if(curtemperature<settemperature)
                   {
                       openDoor = 1;
                   }
                }
                LogeventEntity templogevent = new LogeventEntity();
                templogevent.setUserId(userId);
                EntityWrapperHandle<UserinfoEntity> ewuseinfo = new EntityWrapperHandle<UserinfoEntity>();
                ewuseinfo.eq("userid", userId);
                List<UserinfoEntity> tmpuserinfo =  userinfoService.selectList(ewuseinfo);
                if(tmpuserinfo!=null&&tmpuserinfo.size()>0)
                {
                    templogevent.setUserName(tmpuserinfo.get(0).getUsername());
                    templogevent.setUserType(tmpuserinfo.get(0).getUsertype());
                    templogevent.setSex(tmpuserinfo.get(0).getSex());
                    templogevent.setTemplateimgurl(tmpuserinfo.get(0).getUserimageurl());
                }
                else
                {
                    templogevent.setUserName(userName);
                    templogevent.setUserType(userType);
                }
                templogevent.setAction(action);
                templogevent.setActionCode(actionCode);
                templogevent.setTemperature(jsontemperature);
                templogevent.setDeviceid(deviceid);
                templogevent.setMask(isMask==false?1:0);
                Double temp =  Double.valueOf(jsontemperature);
                if(  temp<37.30 )
                {
                    templogevent.setOpenCode(1);
                }
                else
                {
                    templogevent.setOpenCode(0);
                }
                templogevent.setOpenMsg(openMsg);
                templogevent.setUuid(curdevicesetting.getUuid());
                templogevent.setNationCode(nationCode);
                templogevent.setScreenTime(screenTime);
                templogevent.setSimilarity(similarity);
                try
                {
                    BASE64Decoder decoder = new BASE64Decoder();
                    String format = "yyyy-MM-dd";
                    SimpleDateFormat sdf = new  SimpleDateFormat(format);
                    String curDate =  sdf.format(new Date());
                    String imgpath = curDate+deviceid+System.currentTimeMillis()+".jpg";
                    File file = new File("/images/"+imgpath);
                    if (!file.exists())
                    {
                        file.createNewFile();
                    }
                    byte[] buf = decoder.decodeBuffer(img);
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(buf);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    templogevent.setImgurl("http://healthy-backend-gcgs-cx-gc-20200902.ccsyun.vip/dataimages/"+imgpath);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                logeventService.insert(templogevent);
                return new SyfaceReturnEntity<String>().ok("0",openDoor,unlockDelay);
            }
        }
        return new SyfaceReturnEntity<String>().error(" DeviceSetting is null",20);
    }
}